package com.qf.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.qf.pojo.repVo.BaseResp;
import com.qf.service.CourseService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    CourseService courseService;

    /**
     * 通过课程分类查询课程信息
     * @param id
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/findCourseByClassify/{id}/{page}/{size}")
    public BaseResp findCourseByClassify(@PathVariable("id")Integer id,
                                         @PathVariable("page")Integer page,
                                         @PathVariable("size")Integer size){
        return courseService.findCourseByClassify(id,page,size);
    }
    /**
     * 查询课程的详情信息
     */
    @RequestMapping("/findCourseDetailById/{id}")

    //@HystrixCommand(fallbackMethod = "findCourseDetailByIdFallBack") 接口出现错误时
//    @HystrixCommand(commandProperties = {
//            //策略使用thread的线程池
//            @HystrixProperty(name="execution.isolation.strategy",value = "THREAD"),
//            //当前线程的超时时间，如果超过配置的时间，则直接熔断
//            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000"),
//    },fallbackMethod = "findCourseDetailByIdFallBack") //接口的处理时间
    //配置断路器
    @HystrixCommand(fallbackMethod = "findCourseDetailByIdFallBack",commandProperties = {
            @HystrixProperty(name="execution.isolation.strategy",value = "THREAD"),
//            //当前线程的超时时间，如果超过配置的时间，则直接熔断
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000"),
            @HystrixProperty(name="circuitBreaker.enabled",value = "true"),
            //失败阀值的总请求数
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10"),
            //总请求数的失败率达到%时
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "50"),
            //open状态后，多少秒拒绝请求
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "5000"),
    })
    public BaseResp findCourseDetailById(@PathVariable("id")Integer id){

        return courseService.findCourseDetailById(id);
    }

    /**
     * 熔断的退路方法要与接口方法保持一致。返回值，参数必须一致。
     * 1.当接口出现了异常时，直接走快速的失败方法。
     * 2.当接口处理时间过长时 导致线程的大量堆积，就有可能导致我们的服务的资源耗尽，导致宕机
     * @param id
     * @return
     */
    public BaseResp findCourseDetailByIdFallBack(@PathVariable("id")Integer id){
        System.out.println("课程id："+id+"的接口请求出现了异常！，快速熔断失败！");
        return new BaseResp(0,"快速失败！",null,null);
    }
}
